/**
 * 隐患上报 编辑页
 *
 * 作者 wanghw
 * 日期 2024-08-20 09:23:04
 */
layui.use(['jquery','febs', 'form', 'validate', 'fileUpload', 'fileUpload','autocomplete','commonJS','laydate'], function () {
    var $ = layui.$,
        febs = layui.febs,
        layer = layui.layer,
        form = layui.form,
        $view = $('#hazardReportPlan-edit'),
        $hazardOperation = $view.find('#hazardOperation'),
        $unsafeName = $view.find('#unsafeName'),
        $userManage = $('#userManage'),
        fileUpload = layui.fileUpload,
        autocomplete = layui.autocomplete,
        commonJS = layui.commonJS,
        laydate=layui.laydate,
        validate = layui.validate;

    form.verify(validate);
    form.render();
    initSelect();
    initDate()
    initImg();
    initDetailTale();

    function initDate() {
        if(hazardReport.forwardFlg =='2'){
            return;
        }
        laydate.render({
            elem: "#rectificationDate",
            type: 'datetime',
            value:new Date(),
            btns:['now','confirm']

        })
    }
    function initSelect() {
        if(hazardReport.forwardFlg  =='2'){
            return;
        }
        initProject(getTenantId());
        febs.initDictItemSelect($unsafeName,'SAFETY_HAZARD_UNSAFE_FORM', getUnsafeName(),null);
    }
    febs.initDictItemSelect($unsafeName,'SAFETY_HAZARD_UNSAFE_FORM', getUnsafeName(),null);
    function getUnsafeName(){
        if(hazardReport && hazardReport.unsafeName){
            return hazardReport.unsafeName
        }else {
            return  null
        }
    }


    function initImg() {
        if(hazardReport.fileList){
            var fileUploadDiv = fileUpload.render({
                elem: '#fileUpload',
                url: '',
                type: 0,//0-图片，1-视频，2-其他
                maxNum:5,
                defaultData: getFileList(),
                isDetail: true,
                done: function (res) {
                },
            });
        }
    }

    function getFileList() {
        if (hazardReport && hazardReport.fileList.length>0) {
            return  hazardReport.fileList;
        }else {
            return  [];
        }
    }


    form.on('submit(hazardReportPlan-edit-form-submit)', function (data) {
        if(data.field.status == '11'){
            data.field.rectificationMeasures = data.field.auditReason;
        }
        if(data.field.status == '3' && commonJS.isEmpty(data.field.hazardOperation)){
            febs.modal.warn("请选择正确的隐患类型!");
            return false;
        }
        addOrUpdate(data.field);
        return false;
    });

    function addOrUpdate(data) {
        if(hazardReport.forwardFlg=='2'){
            febs.modal.confirm('提交审核信息', '确定提交信息？', function () {
                febs.postArray(ctx + 'auditForwardTo', data, function () {
                    layer.closeAll();
                    febs.alert.success('提交成功');
                    $('#febs-hazardReportPlan').find('#query').trigger('click');
                });

            });
        }else {
            if(data.status == '11'){
                febs.modal.confirm('退回整改信息', '确定退回信息？', function () {
                    febs.postArray(ctx + 'hazardReportPlan', data, function () {
                        layer.closeAll();
                        febs.alert.success('提交成功');
                        $('#febs-hazardReportPlan').find('#query').trigger('click');
                    });

                });
            }else {
                febs.modal.confirm('保存整改信息', '确定提交信息？', function () {
                    febs.postArray(ctx + 'hazardReportPlan', data, function () {
                        layer.closeAll();
                        febs.alert.success('提交成功');
                        $('#febs-hazardReportPlan').find('#query').trigger('click');
                    });

                });
            }

        }


    }


    form.on('radio(planStatus)',function (obj){
        if(obj.value == '3'){
            //整改
            $("#rectification").removeClass('febs-hide');
            $("#reback").addClass('febs-hide');
            $view.find('textarea[name="auditReason"]').attr("lay-verify","");
            $view.find('textarea[name="auditReason"]').val('');
            $view.find('input[name="leaderName"]').attr("lay-verify","required");
            $view.find('select[name="unsafeName"]').attr("lay-verify","required");
            $view.find('input[name="typeName"]').attr("lay-verify","required");
            $view.find('textarea[name="rectificationMeasures"]').attr("lay-verify","required")
            $view.find('select[name="projectId"]').val("lay-verify","required");
            $view.find('select[name="areaId"]').val("lay-verify","required");
        }else {
            //制定退回
            $("#rectification").addClass('febs-hide');
            $("#reback").removeClass('febs-hide');
            $view.find('textarea[name="auditReason"]').attr("lay-verify","required")
            $view.find('input[name="leaderName"]').attr("lay-verify","");
            $view.find('input[name="leaderName"]').val('');
            $view.find('select[name="unsafeName"]').attr("lay-verify","");
            $view.find('input[name="typeName"]').attr("lay-verify","");
            $view.find('input[name="typeName"]').val('');
            $view.find('textarea[name="rectificationMeasures"]').attr("lay-verify","");
            $view.find('textarea[name="rectificationMeasures"]').val('');
            $view.find('select[name="projectId"]').val('');
            $view.find('select[name="projectId"]').attr("lay-verify","");
            $view.find('select[name="areaId"]').val('');
            $view.find('select[name="areaId"]').attr("lay-verify","");
        }

    })

    form.on('radio(forwardStatus)',function (obj){
        if(obj.value == '1'){
            //整改
            $("#forwardAuditReason").addClass('febs-hide');
            $view.find('textarea[name="auditReason"]').attr("lay-verify","");
        }else {
            //制定退回
            $("#forwardAuditReason").removeClass('febs-hide');
            $view.find('textarea[name="auditReason"]').attr("lay-verify","required")

        }

    })

    $('#inputAuto').autocomplete({
        serviceUrl: ctx + 'common/user/list',//测试接口
        paramName:'keywords',
        useType:'user',
        params:{ tenantId: getTenantId()},
        onSelect: function(suggestion) {
            $view.find("input[name=leaderName]").val(suggestion.value);
            $view.find("input[name=leaderId]").val(suggestion.data);
            $view.find("input[name=leaderNo]").val(suggestion.userNo);
            $view.find("input[name=leaderDeptId]").val(suggestion.deptId);
            $view.find("input[name=leaderDeptName]").val(suggestion.deptName);
            $('#deptName').text(suggestion.deptName);
            $('#leaderNo').text(suggestion.userNo);
        },
    });

    $userManage.on('click', function () {
        febs.modal.open('负责人选择', 'common/user', {
            btn: ['确认','关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
            data:{
                tenantId:getTenantId(),
                multiple:false,
            },
            yes: function (index, layero) {
                let selectData = null
                if(typeof getSelectData  === 'function'){
                    selectData = getSelectData()
                }
                $view.find("input[name=leaderName]").val(selectData.uname);
                $view.find("input[name=leaderId]").val(selectData.userId);
                $view.find("input[name=leaderNo]").val(selectData.userNo);
                $view.find("input[name=leaderDeptId]").val(selectData.deptId);
                $view.find("input[name=leaderDeptName]").val(selectData.deptName);
                $('#deptName').text(selectData.deptName);
                $('#leaderNo').text(selectData.userNo);
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });
    });

    $hazardOperation.autocomplete({
        serviceUrl: ctx + 'hazardTypeOperation',//测试接口
        paramName:'typeName',
        useType:'hazardOperation',
        params:{

        },
        onSelect: function(suggestion) {
            console.log('隐患类型'+JSON.stringify(suggestion))
            $view.find('input[name="hazardOperation"]').val(suggestion.data);
        },
    });

    clearHazardOperation = function (obj) {
        console.log('输入框值'+obj.value)
        $view.find('input[name="hazardOperation"]').val('');
    }

    function getTenantId(){
        if(hazardReport){
            return hazardReport.tenantId;
        }else {
            return POPUP_DATA.tenantId;
        }
    }

    function initDetailTale(){
        if(hazardReport.planRecordList){
            planTableIns = febs.table.init({
                elem: $view.find('table[id="hazardReportPlanRecordTable"]'),
                id: 'hazardReportPlanRecordTable',
                page:false,
                skin: '',
                limit:Number.MAX_VALUE,
                cols: [
                    [
                        {type: 'numbers',title:'序号'},
                        {field: 'auditRealName', title: '制定人姓名',  width: 120},
                        {
                            field: 'auditResult', title: '制定结果', width: 100, align: 'center', templet: function (d) {
                                if (d.auditResult == '1') {
                                    return '<span class="layui-badge febs-tag-green">通过</span>';
                                } else {
                                    return '<span class="layui-badge febs-tag-magenta">退回</span>';
                                }
                            }
                        },

                        {field: 'auditReason', title: '制定理由', minWidth: 120 },
                        {field: 'createdTime', title: '制定时间', width: 160,align:'center'},
                    ]
                ],
                data:hazardReport.planRecordList
            });
        }

        if(hazardReport.feedBackRecordList){
            feedBackTableIns = febs.table.init({
                elem: $view.find('table[id="hazardReportFeedBackRecordTable"]'),
                id: 'hazardReportFeedBackRecordTable',
                page:false,
                skin: '',
                limit:Number.MAX_VALUE,
                cols: [
                    [
                        {type: 'numbers',title:'序号'},
                        {field: 'auditRealName', title: '反馈人姓名',  width: 120},
                        {
                            field: 'auditResult', title: '反馈结果', width: 100, align: 'center', templet: function (d) {
                                if (d.auditResult == '1') {
                                    return '<span class="layui-badge febs-tag-green">通过</span>';
                                } else {
                                    return '<span class="layui-badge febs-tag-magenta">退回</span>';
                                }
                            }
                        },

                        {field: 'auditReason', title: '反馈理由', minWidth: 120 },
                        {field: 'createdTime', title: '反馈时间', width: 160,align:'center'}
                    ]
                ],
                data:hazardReport.feedBackRecordList
            });
        }

        if(hazardReport.auditRecordList){
            feedBackTableIns = febs.table.init({
                elem: $view.find('table[id="hazardReportAuditRecordTable"]'),
                id: 'hazardReportAuditRecordTable',
                page:false,
                skin: '',
                limit:Number.MAX_VALUE,
                cols: [
                    [
                        {type: 'numbers',title:'序号'},
                        {field: 'auditRealName', title: '审核人姓名',  width: 120},
                        {
                            field: 'auditResult', title: '审核结果', width: 100, align: 'center', templet: function (d) {
                                if (d.auditResult == '1') {
                                    return '<span class="layui-badge febs-tag-green">审核通过</span>';
                                } else {
                                    return '<span class="layui-badge febs-tag-magenta">审核退回</span>';
                                }
                            }
                        },
                        {field: 'auditReason', title: '审核理由', minWidth: 120 },
                        {field: 'createdTime', title: '审核时间', width: 160,align:'center'}
                    ]
                ],
                data:hazardReport.auditRecordList
            });
        }
        form.render()
    }

    function initProject(tenantId) {
        //初始化项目
        var data = {
            tenantId:tenantId
        };
        $("#projectId").empty();
        //初始化商品单位
        febs.getSync(ctx + 'baseProject', data, function (r) {
            // console.log("项目列表" + JSON.stringify(r.data))
            var areaLis = r.data;
            var options = '<option value="">请选择</option>';
            $.each(areaLis, function (index, item) {
                options += '<option value="' + item.projectId + '" projectManageId="' + item.projectManageId + '"  projectManageName="' + item.projectManageName + '">' + item.projectName + '</option>'
            })
            $("#projectId").append(options);
        });
        form.render();
    }

    form.on('select(projectId)', function(obj){
        // 获取选中项 value
        var projectId = obj.value;
        var selectProject = $view.find("select[name='projectId']").find("option:selected");
        if(projectId == ''){
            $("#areaId").empty();
            $view.find('input[name="projectName"]').val("");
        }else {
            initProjectAreaId()
            $view.find('input[name="projectName"]').val(selectProject.text());
        }
        form.render();
    });
    function initProjectAreaId(projectId) {
        if(!projectId){
            projectId = $view.find('select[name="projectId"]').find("option:selected").val();
        }
        //初始化项目区域
        var data ={
            tenantId:getTenantId(),
            projectId:projectId
        };
        $("#areaId").empty();
        febs.getSync(ctx + 'baseProjectArea', data, function (r) {
            // console.log("区域列表" + JSON.stringify(r.data))
            var resultData = r.data;
            var options = '<option value="">请选择</option>';
            $.each(resultData, function (index, item) {
                options += '<option value="' + item.areaId + '">' + item.areaName + '</option>'
            })
            $("#areaId").append(options);
        });
    }

    form.on('select(areaId)', function(obj){
        var areaId = obj.value;
        // 获取选中项 value
        var areaName = $view.find("select[name='areaId']").find("option:selected").text();
        if(areaId == ''){
            $view.find('input[name="areaName"]').val("");
        }else {
            $view.find('input[name="areaName"]').val(areaName);
        }
        form.render();
    });


    form.on('input-affix(addHazardOperation)', function(obj){
        febs.modal.open('违章类型选择', 'common/hazardType', {
            btn: ['确认','关闭'],
            area: $(window).width() <= 750 ? ['95%', '85%']: ['80%', '85%'],
            data:{
                tenantId:getTenantId(),
                multiple:false,
            },
            yes: function (index, layero) {
                let selectData = null
                if(typeof getSelectData  === 'function'){
                    selectData = getSelectData()
                }
                console.log("为扎根类型"+JSON.stringify(selectData));
                $view.find('input[name="hazardOperation"]').val(selectData.typeOperationId);
                $view.find('input[id="hazardOperation"]').val(selectData.typeName);
                layer.close(index);
            },
            btn2: function (index, layero) {
                layer.close(index);
                return false;
            }
        });
    });




});